<?php
class AccountModel extends Model {
	 public function __construct() {
			 parent::Model();
			 $this->load->model("ContactModel");
			 $this->load->model("LocationsModel");
			 $this->load->model("Login");		 
		 }
	 public function getUserId($username) {
			 $p_id="";
			 $rs = $this->db->query("SELECT profile.p_id FROM profile,users WHERE profile.p_id=users.p_id AND users.username=?",array($username));
			 if($rs->num_rows()>0) { 
					 $p_id = $rs->row()->p_id;
				 }
			 return $p_id;
		 }
	 public function updateAccount($pDataArray,$cDataArray,$uDataArray,$lDataArray,$now) {
			 $rs = $this->db->query("SELECT profile.p_id,profile.contact_id,profile.location_id FROM profile,users WHERE users.p_id=profile.p_id AND users.username=?",array($pDataArray["username"]));
			 if($rs->num_rows()>0) { 
					 $p_id = $rs->row()->p_id;
					 $c_id = $rs->row()->contact_id;
					 $l_id = $rs->row()->location_id;
					 // setup Location
					 if($l_id!="")
						$this->LocationsModel->update($lDataArray,$c_id,$l_id);
					 else
						$l_id = $this->LocationsModel->create($lDataArray,$c_id);
					 // setup contact
					 if($c_id!="")
						$this->ContactModel->update($cDataArray,$c_id);
					 else
						$c_id = $this->ContactModel->create($cDataArray);

					 // update profile id
					 $this->db->query("UPDATE profile SET aha_number=?,fname=?,lname=?,last_updated=?,location_id=?,contact_id=? WHERE p_id=?", array($pDataArray["aha_number"],$pDataArray["fname"],$pDataArray["lname"],$now,$l_id,$c_id,$p_id));
echo "<h2>" . $this->db->last_query() . "</h2>";
					 if($uDataArray["passwd"]!="") {
							 $this->db->query("UPDATE users SET passwd=? WHERE username=?",array($uDataArray["passwd"],$uDataArray["username"]));
						 }
				 }// end check if profile exist
		 }
	 public function createAccount($pDataArray,$cDataArray,$uDataArray,$lDataArray,$now){
			 $this->db->query("INSERT INTO profile (forum_username,created_date,aha_number,fname,lname,last_updated) VALUES(?,?,?,?,?,?)", array($uDataArray["username"],$now,$pDataArray["aha_number"],$pDataArray["fname"],$pDataArray["lname"],$now));
			 $rs = $this->db->query("SELECT LAST_INSERT_ID() as p_id FROM profile");
			 $p_id = $rs->row()->p_id;
			 if($rs->num_rows()>0){
					 $p_id = $rs->row()->p_id;
					 $this->Login->createUser($p_id,$uDataArray["username"],$uDataArray["passwd"]);
					 $c_id = $this->ContactModel->create($cDataArray);
					 $this->LocationsModel->create($lDataArray,$c_id);
					 if($c_id>=0){
							 $this->db->query("UPDATE profile SET contact_id=? WHERE p_id=?",array($c_id,$p_id));
						 }
				 }
			 if ($this->db->trans_status() === FALSE)
				 {
				 //$this->db->trans_rollback();
				 } else {
				 //$this->db->trans_commit();
				 }
		 }
}
?>